package com.gdpu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.gdpu.config.OssConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;


/**
 * @Author:weiming
 * @Date:2020/12/1
 */
@Service
public class OssService {

    @Autowired
    private OssConfig ossConfig;

    private Logger logger = LoggerFactory.getLogger(OssService.class);

    /**
     * Minio对象文件上传
     * @param file
     */
    public String minioUpload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(ossConfig.endpoint, ossConfig.accessKeyId, ossConfig.accessKeySecret);
        try {
            // 检查存储桶是否已经存在
            boolean isExist = ossClient.doesBucketExist(ossConfig.bucketName);
            if(isExist) {
                logger.info("Bucket already exists.");
            } else {
                // 创建存储桶
                ossClient.createBucket(ossConfig.bucketName);
            }
            String key = ossConfig.filePathPrefix+"/"+file.getOriginalFilename();
            PutObjectResult result = ossClient.putObject(ossConfig.bucketName, key, file.getInputStream());
            String objUrl = "http://"+ossConfig.siteName+"/"+key;

            return objUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return "上传失败";
    }
}
